﻿Imports TBCC.UserManage
Public Class TimeSetForm

    Private _pi As ProjectItem
    '起始地址
    Private _offset As UShort = 0
    Private _offset_Time As UShort = 10   '20100727更新系统时钟校准时，读取基准时间地址
    Private _offset_val As UShort = 11   '数据上传控制参数地址
    Private buf1() As UShort
    '选择设备的网络地址
    Private _netID As Byte
    Private result As Integer
    Private _ReadTime As Boolean
    Private _ReadString As String
    Private _Second As Integer = 60   '数据偏差时间
    '时间参数数据
    Private _buf() As Short
    Private bufTime() As Short

    Private Sub TimeSetForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        _pi = MainForm.pi
        _netID = DevTypeService.GetMinDevId(_pi.ProjectID)
        CheckUserRight(MainForm)
        EnableModify(False)
        Me.btnModify.Enabled = False
        Me.Btn_SetTime.Enabled = False
        Me.btnShowDevTime.Enabled = False
        Timer1.Start() ' LoadData()
#If LSC_PROJECTTYPE_SWITCH = "SALES" Then
        Me.btnOk.Visible = False
#End If

    End Sub
    Private Sub CheckUserRight(ByVal frm As MainForm)
        Dim gp As System.Security.Principal.GenericPrincipal
        gp = My.User.CurrentPrincipal

        If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
            Me.btnModify.Visible = True
            Me.btnOk.Visible = True
            Me.Btn_SetTime.Visible = True

        Else
            Me.btnModify.Visible = False
            Me.btnOk.Visible = False
            Me.Btn_SetTime.Visible = False
        End If
    End Sub
    Private Function readalldev() As Integer
        Dim dts As New DevTypeService(_pi)
        Dim k As Integer

        Me.Cursor = Cursors.WaitCursor
        k = RefreshData()
        For Each dti As DevTypeItem In dts.GeDevGroupList()   '设备列表

            Try
                buf1 = COMHelper.Instance.Send4UShort(dti.NetId, FunctionCode.WordWritableRead, _offset_val, 1)

            Catch ex As Exception
                Debug.WriteLine(ex.Message)
            Finally
                Me.Cursor = Cursors.Default
            End Try

            If buf1 Is Nothing Then
                Me.btnModify.Enabled = False
                ' ClearData()
                msg.ShowError("读取参数失败")
                Return 0
            End If


            If k = buf1(0) Then
                ' Me.btnModify.Enabled = True
            Else

                Return 0
                'Me.btnModify.Enabled = False
                msg.ShowError("读取参数失败")
            End If
        Next



        Return k

    End Function
    Private Function RefreshData() As Integer
        Try
            buf1 = COMHelper.Instance.Send4UShort(_netID, FunctionCode.WordWritableRead, _offset_val, 1)

        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try

        If buf1 Is Nothing Then
            Me.btnModify.Enabled = False
            ' ClearData()
            msg.ShowError("读取参数失败")
            Return False
        End If

        Return buf1(0)

    End Function


    Private Function LoadData() As Boolean
        '  Dim result As Integer '= readalldev() 20100727更新系统时钟校准时，不需要根据启停而修改时钟
        If g_test Then
            ReDim _buf(200)
            For i As Integer = 0 To _buf.Length - 1
                _buf(i) = g_rand.Next(1, 12)
            Next
        Else
            Try
                _buf = COMHelper.Instance.Send4Short(g_netID, FunctionCode.WordReadonly, _offset_Time, 7) '读1号子控时间 _offset_Time20100727更新系统

            Catch ex As Exception

            End Try

            If _buf Is Nothing Then
                msg.ShowError("读取基准时钟失败！")
                'Me.nudYear.Minimum = 0
                ' Me.nudYear.Value = 0
                Me.btnModify.Enabled = False
                ' Me.btnShowDevTime.Enabled = False
                '  msg.ShowError("读取参数失败")
                _ReadTime = False

                Return False
            ElseIf _buf(0) < 0 OrElse _buf(1) < 0 OrElse _buf(2) < 0 OrElse _buf(3) < 0 OrElse _buf(4) < 0 OrElse _buf(5) < 0 Then
                Me.btnModify.Enabled = False
                Me.btnShowDevTime.Enabled = False

                _ReadTime = False
                '  msg.ShowError("读取参数失败")
                Return False
            Else
                _ReadTime = True

            End If
        End If

        Try
            Me.nudYear.Value = _buf(0)
            Me.nudMonth.Value = _buf(1)
            Me.nudDay.Value = _buf(2)
            Me.nudHour.Value = _buf(3)
            Me.nudMinute.Value = _buf(4)
            Me.nudSecond.Value = _buf(5)
        Catch ex As Exception
            msg.ShowError(ex.Message)
        End Try


        'If result = 1 Then   20100727更新系统时钟校准时，不需要根据启停而修改时钟
        '    Me.btnModify.Enabled = True
        'Else
        '    Me.btnModify.Enabled = False
        'End If







        Return True


    End Function

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub



    Private Sub EnableModify(ByVal value As Boolean)
        'If result = 1 Then
        '    Me.btnModify.Enabled = Not value
        'Else
        '    Me.btnModify.Enabled = False
        'End If

        ' Me.btnModify.Enabled = Not value
        Me.btnOk.Enabled = value
        Me.btnShowDevTime.Enabled = Not value

        Me.nudYear.ReadOnly = Not value
        Me.nudMonth.ReadOnly = Not value
        Me.nudDay.ReadOnly = Not value
        Me.nudHour.ReadOnly = Not value
        Me.nudMinute.ReadOnly = Not value
        Me.nudSecond.ReadOnly = Not value

        Dim i As Integer
        If value Then
            i = 1
        Else
            i = 0
        End If

        Me.nudYear.Increment = i
        Me.nudMonth.Increment = i
        Me.nudDay.Increment = i
        Me.nudHour.Increment = i
        Me.nudMinute.Increment = i
        Me.nudSecond.Increment = i

    End Sub

    Private Sub btnModify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnModify.Click

        Me.GroupBox2.Text = "设置时间"
        Me.btnModify.Enabled = False
        Me.Btn_SetTime.Enabled = False
        EnableModify(True)
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Dim result As Boolean
        Me.Cursor = Cursors.WaitCursor
        result = Save(1)
        Me.Cursor = Cursors.Default

        If result Then
            msg.Show("保存成功")
            LoadData()
            Me.btnModify.Enabled = True
            Me.Btn_SetTime.Enabled = True
        Else
            Exit Sub
        End If

        Me.GroupBox2.Text = "基准时钟时间"
        EnableModify(False)
    End Sub

    ''' <summary>
    ''' 保存数据
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Save(ByVal valueEn As Integer) As Boolean
        Dim value As Short

        Dim result As Boolean = False

        If valueEn = 1 Then
            value = Me.nudYear.Value '- 1900
            If Not Write(0, value) Then
                GoTo WriteERROR
            End If
            Sleep()

            value = Me.nudMonth.Value
            If Not Write(1, value) Then
                GoTo WriteERROR
            End If
            Sleep()

            value = Me.nudDay.Value
            If Not Write(2, value) Then
                GoTo WriteERROR
            End If
            Sleep()

            value = Me.nudHour.Value
            If Not Write(3, value) Then
                GoTo WriteERROR
            End If
            Sleep()

            value = Me.nudMinute.Value
            If Not Write(4, value) Then
                GoTo WriteERROR
            End If
            Sleep()

            value = Me.nudSecond.Value
            If Not Write(5, value) Then
                GoTo WriteERROR
            End If
            Sleep()


        End If

        'value = Me.nudWeek.Value
        'COMHelper.Instance.Broadcast(functionCode, 6, value)
        'sleep()

        '修改使能位
        value = valueEn
        If Not Write(7, value) Then
            GoTo WriteERROR
        End If

        GoTo WriteSUCCESS

WriteERROR:
        msg.ShowError("修改时间失败")
        Return False

WriteSUCCESS:
        Return True

    End Function

    Private Function ReadAllDevTime() As String

        ReadAllDevTime = String.Empty
        Dim str As String = Nothing
        Dim str_Time As String = Nothing

        str_Time = _ReadDevTimeS(255)   '20100727修改读取基准时钟时间
        If str_Time IsNot Nothing Then
            ReadAllDevTime &= str_Time & vbCrLf
        Else
            ReadAllDevTime &= "基准时钟时间：" & g_strReadError & vbCrLf
            ' msg.ShowError(g_strReadError)
            '  Return Nothing
        End If


        str = _ReadDevTime(255)    '读取通讯模块系统时钟
        If str IsNot Nothing Then
            ReadAllDevTime &= str & vbCrLf
        Else
            ReadAllDevTime &= "通讯设备系统时间：" & g_strReadError & vbCrLf
            '  msg.ShowError(g_strReadError)
            ' Return Nothing
        End If

        If MainForm.pi.DevTypeGroupList.Count > 0 Then
            For Each item As DevTypeItem In MainForm.pi.DevTypeGroupList

                Try
                    str = _ReadDevTime(item.NetId)
                    If str IsNot Nothing Then
                        ReadAllDevTime &= str & vbCrLf
                    Else
                        ReadAllDevTime &= item.NetId & "号设备系统时间：" & g_strReadError & vbCrLf
                        'ReadAllDevTime = String.Empty
                        'msg.ShowError(g_strReadError)
                        'Exit Function
                    End If
                Catch ex As Exception
                    ReadAllDevTime = String.Empty
                    msg.ShowError(ex.Message)
                    Return Nothing
                End Try
            Next

        End If


        If CcapDevItemService.GetCcapDevTypeList(_pi).Count > 0 Then

            For Each item As CcapDevItem In CcapDevItemService.GetCcapDevTypeList(_pi)

                Try
                    str = _ReadDevTime(item.NetId)
                    If str IsNot Nothing Then
                        ReadAllDevTime &= str & vbCrLf
                    Else
                        ReadAllDevTime &= item.NetId & "号设备系统时间：" & g_strReadError & vbCrLf
                        'ReadAllDevTime = String.Empty
                        'msg.ShowError(g_strReadError)
                        'Exit Function
                    End If
                Catch ex As Exception
                    ReadAllDevTime = String.Empty
                    msg.ShowError(ex.Message)
                    Return Nothing
                End Try
            Next


        End If


    End Function

    Private Function ComTime() As String

        _ReadString = String.Empty

        ComTime = String.Empty
        Dim str As String = Nothing
        Dim str1() As Short = Nothing
        Dim str_Time As DateTime = DateTime.MinValue
        Dim RTC_Time As DateTime

        Dim ExTime As DateTime

        _ReadDevTimeS(255)

        If bufTime Is Nothing Then
            ' ComTime = String.Empty
            msg.ShowError("读取不到基准时钟！")
            _ReadString &= "基准时钟时间：" & g_strReadError & vbCrLf
            ComTime = UtilityClass.GetDateString(DateTime.MinValue)
        Else

            str_Time = New DateTime(bufTime(0), bufTime(1), bufTime(2), bufTime(3), bufTime(4), bufTime(5))   '20100727修改读取基准时钟时间
            RTC_Time = str_Time
            _ReadString &= "基准时钟时间：" & str_Time & vbCrLf
        End If


        str1 = __ReadDevTime(255)    '读取通讯模块系统时钟


        If str1 IsNot Nothing Then

            ExTime = New DateTime(str1(0), str1(1), str1(2), str1(3), str1(4), str1(5))
            If ComTime = UtilityClass.GetDateString(DateTime.MinValue) Then
            Else
                If RTC_Time.AddSeconds(-_Second) > ExTime OrElse RTC_Time.AddSeconds(_Second) < ExTime Then
                    ComTime &= "通讯设备系统时间：" & ExTime & vbCrLf

                End If

            End If

            _ReadString &= "通讯设备系统时间：" & ExTime & vbCrLf
           

        Else
            _ReadString &= "通讯设备系统时间：" & g_strReadError & vbCrLf
        End If



        If MainForm.pi.DevTypeGroupList.Count > 0 Then
            For Each item As DevTypeItem In MainForm.pi.DevTypeGroupList
                str1 = Nothing
                Try
                    str1 = __ReadDevTime(item.NetId)

                    If str1 IsNot Nothing Then
                       

                        ExTime = New DateTime(str1(0), str1(1), str1(2), str1(3), str1(4), str1(5))

                        If ComTime = UtilityClass.GetDateString(DateTime.MinValue) Then

                        Else
                            If RTC_Time.AddSeconds(-_Second) > ExTime OrElse RTC_Time.AddSeconds(_Second) < ExTime Then
                                ComTime &= item.NetId & "号设备系统时间：" & ExTime & vbCrLf

                            End If

                        End If

                        _ReadString &= item.NetId & "号设备系统时间：" & ExTime & vbCrLf
                        
                    Else
                        _ReadString &= item.NetId & "号设备系统时间：" & g_strReadError & vbCrLf
                       
                    End If
                Catch ex As Exception
                    ComTime = String.Empty
                    msg.ShowError(ex.Message)
                    Return Nothing
                End Try
            Next

        End If


        If CcapDevItemService.GetCcapDevTypeList(_pi).Count > 0 Then

            For Each item As CcapDevItem In CcapDevItemService.GetCcapDevTypeList(_pi)
                str1 = Nothing

                Try
                    str1 = __ReadDevTime(item.NetId)

                    If str1 IsNot Nothing Then
                        ExTime = New DateTime(str1(0), str1(1), str1(2), str1(3), str1(4), str1(5))
                        If ComTime = UtilityClass.GetDateString(DateTime.MinValue) Then

                        Else
                            'If Math.Abs(DateTime.Compare(RTC_Time, ExTime)) >= 10 Then
                            '    ComTime &= str & vbCrLf

                            'End If

                            If RTC_Time.AddSeconds(-_Second) > ExTime OrElse RTC_Time.AddSeconds(_Second) < ExTime Then
                                ComTime &= item.NetId & "号设备系统时间：" & ExTime & vbCrLf

                            End If


                        End If

                        _ReadString &= item.NetId & "号设备系统时间：" & ExTime & vbCrLf

                    Else
                        _ReadString &= item.NetId & "号设备系统时间：" & g_strReadError & vbCrLf


                    End If
                Catch ex As Exception
                    ComTime = String.Empty
                    msg.ShowError(ex.Message)
                    Return Nothing
                End Try
            Next


        End If

    End Function
    Private Function _ReadDevTime(ByVal netID As Integer) As String
        _ReadDevTime = String.Empty

        If g_test Then
            ReDim _buf(200)
            For i As Integer = 0 To _buf.Length - 1
                _buf(i) = g_rand.Next(1, 12)
            Next
        Else
            _buf = __ReadDevTime(netID)
            If _buf Is Nothing Then
                'Me.nudYear.Minimum = 0
                'Me.nudYear.Value = 0
                'Me.btnModify.Enabled = False
                Return Nothing
            End If
        End If

        If netID = 255 Then
            _ReadDevTime &= " 通讯设备系统时间："
        Else
            _ReadDevTime &= netID & "号设备系统时间："
        End If

        'If netID = g_netID Then
        '    Me.nudYear.Value = _buf(0)
        '    Me.nudMonth.Value = _buf(1)
        '    Me.nudDay.Value = _buf(2)
        '    Me.nudHour.Value = _buf(3)
        '    Me.nudMinute.Value = _buf(4)
        '    Me.nudSecond.Value = _buf(5)
        'End If

        _ReadDevTime &= String.Format("{0:D4}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", _
            _buf(0), _buf(1), _buf(2), _buf(3), _buf(4), _buf(5))

    End Function
    Private Function _ReadAllDevTime(ByVal netID As Integer) As DateTime
        ' _ReadDevTime = String.Empty

        If g_test Then
            ReDim _buf(200)
            For i As Integer = 0 To _buf.Length - 1
                _buf(i) = g_rand.Next(1, 12)
            Next
        Else
            _buf = __ReadDevTime(netID)
            If _buf Is Nothing Then
                ' Me.nudYear.Minimum = 0
                ' Me.nudYear.Value = 0
                'Me.btnModify.Enabled = False
                Return Nothing
            End If
        End If


    End Function
    Private Function _ReadDevTimeS(ByVal netID As Integer) As String
        _ReadDevTimeS = String.Empty

        If g_test Then
            ReDim _buf(200)
            For i As Integer = 0 To _buf.Length - 1
                _buf(i) = g_rand.Next(1, 12)
            Next
        Else
            _buf = COMHelper.Instance.Send4Short(netID, FunctionCode.WordReadonly, _offset_Time, 7) '读1号子控时间
            If _buf Is Nothing Then
                ' Me.nudYear.Minimum = 0
                ' Me.nudYear.Value = 0
                'Me.btnModify.Enabled = False
                _ReadTime = False
                Return Nothing
            Else
                _ReadTime = True
            End If
        End If

        bufTime = _buf


        _ReadDevTimeS &= " 基准时钟系统时间："



        Me.nudYear.Value = _buf(0)
        Me.nudMonth.Value = _buf(1)
        Me.nudDay.Value = _buf(2)
        Me.nudHour.Value = _buf(3)
        Me.nudMinute.Value = _buf(4)
        Me.nudSecond.Value = _buf(5)


        _ReadDevTimeS &= String.Format("{0:D4}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", _
            _buf(0), _buf(1), _buf(2), _buf(3), _buf(4), _buf(5))

    End Function
    Private Function __ReadDevTime(ByVal netID As Integer) As Short()

        If g_test Then
            ReDim _buf(200)
            For i As Integer = 0 To _buf.Length - 1
                _buf(i) = g_rand.Next(1, 12)
            Next
        Else
            _buf = COMHelper.Instance.Send4Short(netID, FunctionCode.WordReadonly, _offset, 7) '读1号子控时间
        End If

        Return _buf
    End Function

    Private Function Write(ByVal offset As UShort, ByVal value As Short) As Boolean
        'Return COMHelper.Instance.Write(g_broadID, FunctionCode.WordWrite, offset, value) '广播地址
        Return COMHelper.Instance.Write(g_netID, FunctionCode.WordWrite, offset, value) '广播地址
    End Function

    Sub Sleep()
        System.Threading.Thread.Sleep(100)
    End Sub

    Private Sub nudYear_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudYear.ValueChanged

    End Sub

    Private Sub nudMonth_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudMonth.ValueChanged

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        Dim result As Boolean
        Timer1.Stop()
        'Me.btnModify.Enabled = True
        result = LoadData()
        Me.btnShowDevTime.Enabled = True

        If result Then
        Else
            Exit Sub
        End If



        Me.btnModify.Enabled = True   '20100727更新系统时钟校准时，不需要根据启停而修改时钟
        Me.Btn_SetTime.Enabled = True




    End Sub

    Private Sub btnShowDevTime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowDevTime.Click
        sender.Enabled = False
        Me.btnModify.Enabled = False
        Me.Btn_SetTime.Enabled = False

        '比较时钟与基准时钟差距，大于十秒钟提示
        Dim str1 As String
        str1 = ComTime()
        If str1.Length > 0 Then
            msg.Show("以下设备时间与基准时间偏差过大：" & vbCrLf & str1)
        End If

        Dim str As String
        '  str = ReadAllDevTime()
        str = _ReadString
        If str.Length > 0 Then
            msg.Show(str)
        End If

        '  LoadData()
        sender.Enabled = True
        If _ReadTime Then
            Me.btnModify.Enabled = True
            Me.Btn_SetTime.Enabled = True
        Else
            Me.btnModify.Enabled = False
            Me.Btn_SetTime.Enabled = False

        End If
       
    End Sub
   

    Private Sub Btn_SetTime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_SetTime.Click
        Me.btnModify.Enabled = False
        Me.Btn_SetTime.Enabled = False
        Dim str As String
        Dim result As Boolean
        Me.Cursor = Cursors.WaitCursor
        result = Save(2)
        Me.Cursor = Cursors.Default

        If result Then
            msg.Show("强制修改成功！")

            str = ReadAllDevTime()
            If str.Length > 0 Then
                msg.Show(str)
            End If

            Me.btnModify.Enabled = True
            Me.Btn_SetTime.Enabled = True
            EnableModify(False)
        Else
            Me.btnModify.Enabled = True
            Me.Btn_SetTime.Enabled = True
            EnableModify(False)
            Exit Sub
        End If


    End Sub
End Class